//
//  CLDeviceiOSLocationTool.m
//  togetherLBS
//
//  Created by Phyllis Hu on 15/10/30.
//  Copyright (c) 2015年 celi. All rights reserved.
//  手机端定位工具，只能用于获取自己位置

#import "CLDeviceiOSLocationTool.h"

@interface  CLDeviceiOSLocationTool()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager  *locationManager;
@property (nonatomic, assign) CLLocationAccuracy locationAccuracy; //定位精度
@property (nonatomic, strong) CLGeocoder *geocoder;           //编码器
@end

@implementation CLDeviceiOSLocationTool


/**
 *  启动定位服务
 */
- (void)changeLocationWayForActive
{
    //    DLog(@"...active");
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        _locationManager.distanceFilter = 10;
        if ([[[UIDevice currentDevice]systemVersion] compare:@"6.0"] >= 0) {
            _locationManager.pausesLocationUpdatesAutomatically = YES;
            _locationManager.activityType = CLActivityTypeFitness;
        }
        if (kCLAuthorizationStatusNotDetermined == [CLLocationManager authorizationStatus]) {
            if (SysVerValue >= 8) {
                [_locationManager requestWhenInUseAuthorization];
            }else{
                DLog(@"location AuthorizationStatusNotDetermined");
            }
        }else{
            [_locationManager startUpdatingLocation];
        }
    }else{
        [_locationManager stopMonitoringSignificantLocationChanges];
        _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        [_locationManager startUpdatingLocation];
    }
}


/**
 * 创建定位器
 *
     kCLLocationAccuracyBestForNavigation（导航级的最佳精确度）
     kCLLocationAccuracyBest（最佳精确度）
     kCLLocationAccuracyNearestTenMeters（10米误差）
     kCLLocationAccuracyHundredMeters（百米误差）
     kCLLocationAccuracyKilometer（千米误差）
     kCLLocationAccuracyThreeKilometers（三千米误差）
 */
- (instancetype)initWithCLLocationManagerLocationAccuracyType:(CLLocationAccuracy)LocationAccuracyType{

    self = [super init];
    if (self) {
        self.desiredAccuracy = LocationAccuracyType;
        self.delegate = self;
    }
    return self;
}

+ (id)CLLocationManagerWithLocationAccuracyType:(CLLocationAccuracy)LocationAccuracyType{
    
    return [[self alloc]initWithCLLocationManagerLocationAccuracyType:LocationAccuracyType];
}

- (void)dealloc{
    DLog(@"CLDeviceiOSLocationTool-----------");
}

/**
 *   开始定位
 */
- (void)startLocation{
    [self changeLocationWayForActive];
    if ([CLLocationManager locationServicesEnabled]) {
        // 开始定位用户的位置
        [self startUpdatingLocation];
    } else { // 不能定位用户的位置
        //引导用户查看定位服务开启帮助页
        [self showAlertView:CLLocalizedString(@"LocServiceClose", nil)];
    }
}


#pragma mark- show msg
-(void)showAlertView:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:CLLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
    [alert show];
}

#pragma mark - CLLocationManagerDelegate
/**
 *  当定位到用户的位置时，就会调用（调用比较频繁）
 */
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    // 停止更新位置(不用定位服务，应当马上停止定位，非常耗电)
    [manager stopUpdatingLocation];
    
    // 数组里面存放的是CLLocation对象， 一个CLLocation就代表一个位置
    CLLocation *loc = [locations lastObject];
    DLog(@"纬度=%f, 经度=%f", loc.coordinate.latitude, loc.coordinate.longitude);
    
    if([self.locationDelegate respondsToSelector:@selector(CLDeviceiOSLocation:)]){
        [self.locationDelegate CLDeviceiOSLocation:loc];
    }
    [self reverseGeocode:loc.coordinate];
}

/**
 *  编码器
 */
- (CLGeocoder *)geocoder
{
    if (!_geocoder) {
        self.geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

/**
 *  反地理编码：经纬度 -> 地名
 */
- (void)reverseGeocode:(CLLocationCoordinate2D)coordinates
{
    CLLocationDegrees latitude = coordinates.latitude;
    CLLocationDegrees longtitude = coordinates.longitude;
    __weak __typeof(self)weakSelf = self;
    // 开始反向编码
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longtitude];
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error || placemarks.count == 0) {
            DLog(@"你输入的经纬度找不到，可能在火星上");
            DLog(@"latitude=%f--------longtitude=%f",latitude,longtitude);
            [weakSelf reverseGeocode:coordinates];
        } else { // 编码成功（找到了具体的位置信息）
            // 显示最前面的地标信息
            CLPlacemark *firstPlacemark = [placemarks firstObject];
            if([self.locationDelegate respondsToSelector:@selector(CLDeviceiOSLocationName:)]){
                [self.locationDelegate CLDeviceiOSLocationName:firstPlacemark];
            }
        }
    }];
}

@end
